package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerProductDetail;
import com.crm.model.entity.customerManager.CustomerProductDetailMemberCard;
import com.crm.model.entity.customerManager.CustomerProductDetailThroughTrainTax;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.model.vo.systemManager.AloneMemberShipCardImportVO;
import com.crm.model.vo.systemManager.MemberShipCardImportVO;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerProductDetailMemberCardDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:baijian
 * @Date: 2021/6/26 9:19
 */
@Slf4j
public class InsertAloneMemberCardCallable implements Callable<JSONObject> {

    private CustomerDbService customerDbService;
    private UserAccountDbService userAccountDbService;
    private SysCompanyDbService sysCompanyDbService;
    private CustomerContractDbService customerContractDbService;
    private CustomerProductOrderDbService customerProductOrderDbService;
    private CustomerProductDetailMemberCardDbService customerProductDetailMemberCardDbService;
    private FinishOrderDBservice finishOrderDBservice;
    private List<AloneMemberShipCardImportVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;

    public InsertAloneMemberCardCallable(CustomerDbService customerDbService, UserAccountDbService userAccountDbService,
                                         SysCompanyDbService sysCompanyDbService,
                                         CustomerContractDbService customerContractDbService, CustomerProductOrderDbService customerProductOrderDbService,
                                         CustomerProductDetailMemberCardDbService customerProductDetailMemberCardDbService,
                                         FinishOrderDBservice finishOrderDBservice,
                                         List<AloneMemberShipCardImportVO> list, CountDownLatch begin, CountDownLatch end) {
        this.customerDbService = customerDbService;
        this.userAccountDbService = userAccountDbService;
        this.sysCompanyDbService = sysCompanyDbService;
        this.customerContractDbService = customerContractDbService;
        this.customerProductOrderDbService = customerProductOrderDbService;
        this.customerProductDetailMemberCardDbService = customerProductDetailMemberCardDbService;
        this.finishOrderDBservice = finishOrderDBservice;
        this.list = list;
        this.begin = begin;
        this.end = end;
    }

    @SneakyThrows
    @Override
    public JSONObject call() {
        //导入数量
        int importNum = 0;
        //存在的会员卡
        List<Integer> repeatIdStr = new ArrayList();
        //失败的卡
        List<Integer> importFailIdStr = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        for (int i = 0; i < list.size(); i++) {
            AloneMemberShipCardImportVO importVO = list.get(i);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = "2021-11-03 14:59:28";
            Date updateDate = simpleDateFormat.parse(dateStr);

            try {
                CustomerProductDetailMemberCard card = new CustomerProductDetailMemberCard();
                CustomerProductDetailThroughTrainTax customerProductDetailThroughTrainTax = new CustomerProductDetailThroughTrainTax();
                String customerProductDetailMemberCardId = CommonUtils.getGUID();

                card.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
                customerProductDetailThroughTrainTax.setThroughTrainTaxId(CommonUtils.getGUID());

                Date startTm = formatTime(importVO.getStartTm());
                Date createTm = formatTimeSf(importVO.getCreateTm());

                card.setStartTm(startTm);
                card.setCreateTm(createTm);

                if(!StringUtils.isBlank(importVO.getMemberCardNumber())) {
                    CustomerProductDetailMemberCard memberCard = customerProductDetailMemberCardDbService.getCustomerProductDetailMemberCard(importVO.getMemberCardNumber());
                    if(memberCard == null) {
                        card.setMemberCardNumber(importVO.getMemberCardNumber());
                        if(!StringUtils.isBlank(importVO.getMemberCardPassword())) {
                            card.setMemberCardPassword(importVO.getMemberCardPassword());
                        }

                        if(!StringUtils.isBlank(importVO.getCustomerName())) {
                            Customer customer = customerDbService.selectByCustomerName(importVO.getCustomerName());
                            if(customer != null) {
                                card.setCustomerId(customer.getCustomerId());
                            }
                        }

                        if(!StringUtils.isBlank(importVO.getProductPrice())) {
                            String price = importVO.getProductPrice().substring(0, importVO.getProductPrice().length() - 1);
                            card.setProductPrice(new BigDecimal(price));
                        }

                        if(!StringUtils.isBlank(importVO.getOrderNumber())) {
                            CustomerProductOrderVO order = customerProductOrderDbService.getOrderInfoByNumber(importVO.getOrderNumber());
                            if(order != null) {
                                card.setProductOrderId(order.getProductOrderId());
                                card.setOrderNumber(order.getOrderNumber());
                                customerProductDetailThroughTrainTax.setProductOrderId(order.getProductOrderId());
                                //通过订单id和产品分类 会员 1查询产品信息
                                List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1","1", order.getProductOrderId());
                                if(finishOrderProductList != null && finishOrderProductList.size() > 0) {
                                    FinishOrderProduct finishOrderProduct = finishOrderProductList.get(0);
                                    if(finishOrderProduct != null) {
                                        card.setMemberProductCode(finishOrderProduct.getProductCode());
                                        card.setFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());
                                        customerProductDetailThroughTrainTax.setProductCode(finishOrderProduct.getProductCode());
                                        customerProductDetailThroughTrainTax.setFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());
                                    }
                                }
                            }else{
                                card.setOrderNumber(importVO.getOrderNumber());
                            }
                        }

                        if(!StringUtils.isBlank(importVO.getContractNumber())) {
                            CustomerContract contract = customerContractDbService.selectContractByContractNumber(importVO.getContractNumber());
                            if(contract != null) {
                                card.setContractId(contract.getContractId());
                                card.setContractNumber(contract.getContractNumber());
                            }else{
                                card.setContractNumber(importVO.getContractNumber());
                            }
                        }

                        if(!StringUtils.isBlank(importVO.getCompanyName())) {
                            SysCompany sysCompany = sysCompanyDbService.selectSysCompanyByName(importVO.getCompanyName());
                            if(sysCompany != null) {
                                card.setCompanyId(sysCompany.getCompanyId());
                                customerProductDetailThroughTrainTax.setCompanyId(sysCompany.getCompanyId());
                            }
                        }

                        if(!StringUtils.isBlank(importVO.getAccountName())) {
                            UserAccount userAccount = userAccountDbService.selectUserAccountByUserName(importVO.getAccountName());
                            if(userAccount != null) {
                                card.setAccountId(userAccount.getAccountId());
                                card.setCreatePeopleId(userAccount.getAccountId());
                                card.setUpdatePeopleId(userAccount.getAccountId());
                                card.setUpdateTm(updateDate);
                                customerProductDetailThroughTrainTax.setCreatePeopleId(userAccount.getAccountId());
                                customerProductDetailThroughTrainTax.setUpdatePeopleId(userAccount.getAccountId());
                            }
                        }
                        card.setDataSource(1);
                        Boolean bs= customerDbService.addCustomerProductDetailMemberCard(card);

                        if(!StringUtils.isBlank(importVO.getTrainTax())) {
                            customerProductDetailThroughTrainTax.setMemberCardNumber(importVO.getTrainTax());
                        }
                        customerProductDetailThroughTrainTax.setCreateTm(createTm);
                        customerProductDetailThroughTrainTax.setUpdateTm(updateDate);
                        customerProductDetailThroughTrainTax.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
                        customerProductDetailThroughTrainTax.setDataSource(1);
                        if(bs){
                            repeatIdStr.add(i+2);
                            customerDbService.addCustomerProductDetailThroughTrainTax(customerProductDetailThroughTrainTax);
                        }
                    }else {
                        importNum = importNum + 1;
                    }
                }
            } catch (Exception e) {
                importFailIdStr.add(i+2);
                log.error("导入会员卡异常, Exception info : {}", e);
            }
        }

        jsonObject.put("importNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }


    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTime(String date) throws ParseException {
        //同一个Excel有不一样的时间格式……
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(date);
    }

    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTimeSf(String date) throws ParseException {
        //同一个Excel有不一样的时间格式……
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return simpleDateFormat.parse(date);
    }

    public static void main(String[] args) {
        String a = "11元";
        String substring = a.substring(0, a.length() - 1);
        System.out.println(substring);
    }
}
